// (c) Copyright 2013 Stephen Gold <sgold@sonic.net>
// Distributed under the terms of the GNU General Public License

/*
 This file is part of the Bats Game.

 The Bats Game is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by the
 Free Software Foundation, either version 3 of the License, or (at your
 option) any later version.

 The Bats Game is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 for more details.

 You should have received a copy of the GNU General Public License
 along with the Bats Game.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * fragment shader used by matte.j3md
 */
uniform float m_Tex1Scale;
uniform sampler2D m_Tex1;
uniform vec4 g_LightDirection;

varying vec2 texCoord;
#ifdef SPLAT
    uniform float m_Tex2Scale;
    uniform float m_Tex3Scale;
    uniform sampler2D m_Alpha;
    uniform sampler2D m_Tex2;
    uniform sampler2D m_Tex3;
#endif

varying vec3 AmbientSum;
varying vec3 DiffuseSum;
varying vec3 lightVec;
varying vec3 vNormal;

varying vec4 vLightDir;

void main() {
#ifdef SPLAT
    vec3 alpha = texture2D(m_Alpha, texCoord).rgb;
    vec3 c1 = texture2D(m_Tex1, texCoord * m_Tex1Scale).rgb;
    vec3 c2 = texture2D(m_Tex2, texCoord * m_Tex2Scale).rgb;
    vec3 c3 = texture2D(m_Tex3, texCoord * m_Tex3Scale).rgb;
    vec3 diffuseColor = alpha.x * c1 + alpha.y * c2 + alpha.z * c3;
#else
    vec3 diffuseColor = texture2D(m_Tex1, texCoord * m_Tex1Scale).rgb;
#endif

    float spotFallOff = 1.0;
    if (g_LightDirection.w != 0.0) {
        vec3 L = normalize(lightVec.xyz);
        vec3 spotdir = normalize(g_LightDirection.xyz);
        float curAngleCos = dot(-L, spotdir);
        float innerAngleCos = floor(g_LightDirection.w) * 0.001;
        float outerAngleCos = fract(g_LightDirection.w);
        float innerMinusOuter = innerAngleCos - outerAngleCos;
        spotFallOff = (curAngleCos - outerAngleCos) / innerMinusOuter;
        if (spotFallOff <= 0.0) {
            gl_FragColor.rgb = diffuseColor * AmbientSum;
            gl_FragColor.a = 1.0;
            return;
        } else {
            spotFallOff = clamp(spotFallOff, 0.0, 1.0);
        }
    }
    vec3 lightDir = normalize(vLightDir.xyz);
    float cosine = dot(vNormal, lightDir);
    float light = max(0.0, cosine) * vLightDir.w * spotFallOff;
    gl_FragColor.rgb = diffuseColor * (AmbientSum + DiffuseSum * light);
    gl_FragColor.a = 1.0;
}